package utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.sf.json.JSONObject;

public class Check {
	private static Logger logger = LogManager.getLogger(Check.class);

    public static JSONObject check(String beginDate,String endDate,String sensor){
    	JSONObject json = new JSONObject();
    	if(beginDate == null || beginDate.trim().equals("")){
    		json.put("name", "beginDate");
    		json.put(Pub.MESSAGE, "起始日期不能为空");
    		return json;
    	}
    	if(endDate == null || endDate.trim().equals("")){
    		json.put("name", "endDate");
    		json.put(Pub.MESSAGE, "结束日期不能为空");
    		return json;
    	}
    	if(!sensorFormat(sensor)){
    		json.put("name", "sensor");
    		json.put(Pub.MESSAGE, "传感器格式由字母、数字、下划线组成，长度大于0不超过20");
    		return json;
    	}
    	
    	if(dateFormat(beginDate) > dateFormat(endDate)){
    		json.put("name", "beginDate");
    		json.put(Pub.MESSAGE, "起始日期不能晚于结束日期");
    		return json;
    	}
   
    	return json;
    }
    
    private static long dateFormat(String str){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	long millionSeconds = 0;
    	try{
    		millionSeconds = sdf.parse(str).getTime();//毫秒
    	}catch(ParseException e){
    		logger.error(e.toString());
    	}
    	return millionSeconds;
    	
    }
    
    /*
     * sensor验证方式
     * 判断是否是由字母、数、下划线组成，长度大于0不超过20
    */
    private static Boolean sensorFormat(String sensor){
    	boolean contain = false;
    	char[] ch = sensor.toCharArray();
    	if(ch.length>0&&ch.length<=20){
    		for(int i=0;i<ch.length;i++){
    			if(Character.isDigit(ch[i])||Character.isLetter(ch[i])||
    					ch[i]=='_'||ch[i]==','){
    				contain=true;
    			}else{
    				contain = false;
    				break;
    			}
    		}
    }
    	return contain;
    }

}
